﻿using System;
using System.Windows.Data;

namespace personalplaner.common.converters
{
	public class DateTimeToIsoConverter : IValueConverter
	{
		//public static DateTimeToIsoConverter Instance = new DateTimeToIsoConverter();

		#region IValueConverter Members

		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			if (value is DateTime)
			{
				DateTime dt = (DateTime)value;
				return dt.ToString("d");
			}
			if (value is string)
			{
				//20101220
				string str = (string)value;
				if (str.Length != 8)
					return "";

				try
				{
					string year = str.Substring(0, 4);
					string month = str.Substring(4, 2);
					string day = str.Substring(6, 2);

					DateTime dt = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day));
					return dt.ToString("d");
				}
				catch (Exception)
				{
					return "";
				}
			}

			return "";
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			if (targetType == typeof(bool))
			{
				if (value is string)
				{
					if (string.Compare((string)value, "yes", true, culture) == 0)
						return true;
				}

				return false;
			}
			return value;
		}

		#endregion
	}
}
